from rest_framework import serializers
from snippets.models import *
from django.contrib.auth.models import User


# class SnippetSerializer(serializers.Serializer):
#     id = serializers.IntegerField(read_only=True)  # 序列化时使用，反序列化时不用
#     title = serializers.CharField(required=False, allow_blank=True, max_length=100)
#     code = serializers.CharField(style={'base_template': 'textarea.html'})
#     linenos = serializers.BooleanField(required=False)
#     language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
#     style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
#     owner = serializers.ReadOnlyField(source='owner.username')
#
#     # 注意，没有为model的created创建对应的序列化字段
#     def create(self, validated_data):
#
#         """
#         使用验证后的数据，创建一个代码片段对象。使用的是Django的ORM的语法。
#         """
#         return Snippet.objects.create(**validated_data)
#
#     def update(self, instance, validated_data):
#
#         """
#         使用验证过的数据,更新并返回一个已经存在的‘代码片段’对象。依然使用的是Django的ORM语法
#         """
#         instance.title = validated_data.get('title', instance.title)
#         instance.code = validated_data.get('code', instance.code)
#         instance.linenos = validated_data.get('linenos', instance.linenos)
#         instance.language = validated_data.get('language', instance.language)
#         instance.style = validated_data.get('style', instance.style)
#         instance.save()
#         return instance
#
# class UserSerializer(serializers.ModelSerializer):
#     snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
#
#     class Meta:
#         model = User
#         fields = ['id', 'username', 'snippets']


# 在序列化类中没有的created字段，查询时得不到，新增也不需要提交这个字段
# 继承了HyperlinkedModelSerializer就会有url字段
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    # owner.username 的owner代表user对象，
    owner = serializers.ReadOnlyField(source='owner.username')
    # 自定义一个超链接字段，view_name在urls中配置过
    # highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight',format='html')
    class Meta:
        model=Snippet
        fields=('id','title', 'code', 'linenos', 'language', 'style','owner')

class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ['id', 'username', 'snippets']